import Driver from "driver.js"

export interface RoamingBootProps {
  storageKey: string
  steps: {
    name?: string
    element?: string
    title: string
    description: string
    position?: string
    onNext?: (value: Driver) => void
  }[]
  onDone: () => void //下一步/我知道了
  doneCallBack?: any // 引导结束
}

export const romaingSingleFun = ({
  storageKey,
  steps,
  onDone,
  doneCallBack
}: RoamingBootProps) => {
  const driver = new Driver({
    opacity: 0.7,
    animate: true,
    allowClose: false, // Whether the click on overlay should close or not
    closeBtnText: "跳过",
    doneBtnText: "我知道了",
    nextBtnText: "下一步", // 下一步的按钮文案
    onReset: () => {
      //关闭
      onDone()
      localStorage.setItem(storageKey, "1")
    }
  })
  driver.defineSteps(
    steps.map((item, index) => {
      return {
        element: document.getElementsByName(`code_${item.name}`)[0],
        popover: {
          title: `<div>${item.title}<div/>`,
          description: `<div>${
            item.description
          }<div class="steps_num"><div style='font-size: 14px'>${index + 1}/${
            steps.length
          }</div></div></div>`,
          position: item.position
        },
        onNext: () => {
          // const activeElement = driver.getHighlightedElement() as any; //当前高亮元素
          // const activeNode = activeElement.getNode(); //当前节点
          // console.log('--activeNode--',activeNode);
          if (index + 1 < steps.length) {
            const nextStepItem = steps[index + 1]
            const nextNode = document.getElementsByName(
              `code_${nextStepItem.name}`
            )[0]
            const { left, top } = nextNode.getBoundingClientRect()
            const aiWorkDom = document.getElementsByClassName("ai-work")[0]
            // console.log('--aiWorkDom--:', aiWorkDom);
            // console.log('---left,top--:', left, top);
            //注： 新手引导具备，被高亮元素在视口之外，会先滚动到视口之内在高亮的功能，这里兼容 被高亮元素被顶部NavBar 和 顶部 Page tabs 挡住的问题
            if (top < 178 && aiWorkDom) {
              aiWorkDom.scrollTop = 0
            }
          } else if (index + 1 === steps.length) {
            doneCallBack()
          }
          item.onNext?.(driver)
        }
      }
    }) as Driver.Step[]
  )

  driver.start()
}

export class YmTour extends Driver {
  constructor(options?: Driver.DriverOptions) {
    super({
      opacity: 0.7,
      animate: true,
      allowClose: false,
      closeBtnText: "跳过",
      doneBtnText: "我知道了",
      nextBtnText: "下一步",
      ...options
    })
  }

  public defineSteps(steps: Driver.Step[]): void {
    super.defineSteps(steps)
  }
}
